package com.artisan.service.admin.impl;

import com.artisan.common.enums.OrderStateEnum2;
import com.artisan.common.pojo.PageBean;
import com.artisan.common.utils.TimeFormatUtil;
import com.artisan.dao.*;
import com.artisan.medium.admin.pojo.WorkerForm;
import com.artisan.medium.admin.service.WorkerService;
import com.artisan.model.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.ObjectName;
import javax.transaction.Transactional;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by szw on 2017/7/6.
 */
@Service("workerService")
@Transactional
public class WorkerServiceImpl implements WorkerService {

	private static final DecimalFormat format = new DecimalFormat("#0.0");
	private static final DecimalFormat format2 = new DecimalFormat("#0.00");

	@Autowired
	private AddressInfosMapper addressInfosMapper;

	@Autowired
	private WorkerMapper workerMapper;

	@Autowired
	private BusinessWorkerMapper businessWorkerMapper;

	@Autowired
	private WorkerAreaMapper workerAreaMapper;

	@Autowired
	private BusinessTypeMapper businessTypeMapper;

	@Autowired
	private CustomerScoreMapper customerScoreMapper;

	@Autowired
	private CustomerOrderinfoMapper customerOrderinfoMapper;

	@Autowired
	private BusinessMapper businessMapper;

	@Autowired
	private AssessLableMapper assessLableMapper;

	/**
	 * 查询省级列表
	 * @return
	 */
	@Override
	public List<AddressInfos> qProvinces() {
		AddressInfosExample  addressInfosExample = new AddressInfosExample();
		AddressInfosExample.Criteria criteria = addressInfosExample.createCriteria();
		criteria.andPidEqualTo("0");
		List<AddressInfos> addressInfos = addressInfosMapper.selectByExample(addressInfosExample);
		return addressInfos;
	}

	/**
	 * 新增工人信息
	 * @param workerForm
	 */
	@Override
	public void addWorker(WorkerForm workerForm) {

		workerForm.setUpdateTime(new Date());
		if (workerForm.getId() == null) {
			workerForm.setCrtTime(new Date());
			workerMapper.insertSelective(workerForm);
		} else {
			WorkerAreaExample areaExample = new WorkerAreaExample();
			WorkerAreaExample.Criteria areaCriteria = areaExample.createCriteria();
			areaCriteria.andWIdEqualTo(workerForm.getId());
			workerAreaMapper.deleteByExample(areaExample);
			BusinessWorkerExample workerExample = new BusinessWorkerExample();
			BusinessWorkerExample.Criteria busCriteria = workerExample.createCriteria();
			busCriteria.andWIdEqualTo(workerForm.getId());
			businessWorkerMapper.deleteByExample(workerExample);
			workerMapper.updateByPrimaryKeySelective(workerForm);
		}

		if (workerForm.getAreaList() != null && workerForm.getAreaList().size() > 0) {
			for (String areaId : workerForm.getAreaList()) {
				WorkerArea wa = new WorkerArea();
				wa.setAreaId(areaId);
				wa.setwId(workerForm.getId());
				workerAreaMapper.insert(wa);
			}
		}

		if (workerForm.getfBusinessType() != null && workerForm.getfBusinessType().size() > 0) {
			for (Integer busId : workerForm.getfBusinessType()) {
				BusinessWorker bw = new BusinessWorker();
				bw.setbId(busId);
				bw.setwId(workerForm.getId());
				businessWorkerMapper.insert(bw);
			}
		}

		if (workerForm.getwBusinessType() != null && workerForm.getwBusinessType().size() > 0) {
			for (Integer busId : workerForm.getwBusinessType()) {
				BusinessWorker bw = new BusinessWorker();
				bw.setbId(busId);
				bw.setwId(workerForm.getId());
				businessWorkerMapper.insert(bw);
			}
		}
	}

	/**
	 * 工人信息查询
	 * @param busId
	 * @param proId
	 * @param cityId
	 * @param areaId
	 * @param ide
	 * @param phone
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageBean queryWorkers(Integer busId, String proId, String cityId, String areaId, String ide, String phone,
	                             Integer page, Integer pageSize) {

		List<Map<String, Object>> list = new ArrayList<>();

		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("limitStart", (page-1)*pageSize);
		paramMap.put("pageSize", pageSize);
		if(busId != null && busId != -1) {
			paramMap.put("businessId", busId);
		}
		if (StringUtils.isNotBlank(areaId) && !"-1".equals(areaId)) {
			paramMap.put("areaId", areaId);
		} else if (StringUtils.isNotBlank(cityId) && !"-1".equals(cityId)) {
			paramMap.put("cityId", cityId);
		} else if(StringUtils.isNotBlank(proId) && !"-1".equals(proId)) {
			paramMap.put("provinceId", proId);
		}
		if (StringUtils.isNotBlank(ide)) {
			paramMap.put("ide", ide);
		}
		if (StringUtils.isNotBlank(phone)) {
			paramMap.put("phone", phone);
		}

		List<Worker> workers = workerMapper.queryWorkersByMap(paramMap);
		if (workers != null && workers.size() > 0) {
			for (Worker w : workers) {
				Map<String, Object> map = new HashMap<>();
				map.put("worker", w);
				if ("man".equals(w.getSex())) {
					map.put("sex", "男");
				} else {
					map.put("sex", "女");
				}
				map.put("serviceAddr", getServiceAddress(w.getProvinceId(), w.getCityId(), w.getId()));
				map.put("serviceType", getBusinessType(w.getId()));
				map.put("crtTime", TimeFormatUtil.dateToStrFull(w.getCrtTime()));
				map.put("score", getStars(w.getId()));
				list.add(map);
			}
		}

		int count = workerMapper.countByMap(paramMap);

		PageBean<List<Map<String, Object>>> pageBean = new PageBean<>(page, pageSize, count, list);

		return pageBean;
	}

	/**
	 * 工人服务地区
	 * @param proId
	 * @param cityId
	 * @param wId
	 * @return
	 */
	private String getServiceAddress(String proId, String cityId, Integer wId) {
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotBlank(proId)) {
			AddressInfos addr = addressInfosMapper.selectByPrimaryKey(proId);
			sb.append(addr.getName()).append("-");
		}
		if (StringUtils.isNotBlank(cityId)) {
			AddressInfos addr = addressInfosMapper.selectByPrimaryKey(cityId);
			sb.append(addr.getName()).append("-");
		}
		WorkerAreaExample example = new WorkerAreaExample();
		WorkerAreaExample.Criteria criteria = example.createCriteria();
		criteria.andWIdEqualTo(wId);
		List<WorkerArea> areas = workerAreaMapper.selectByExample(example);
		if (areas != null && areas.size() > 0) {
			sb.append("(");
			for (WorkerArea wa : areas) {
				AddressInfos addr = addressInfosMapper.selectByPrimaryKey(wa.getAreaId());
				sb.append(addr.getName()).append("、");
			}
			sb.append(")");
		}
		return sb.toString();
	}

	/**
	 * 工人服务类型
	 * @param wId
	 * @return
	 */
	private String getBusinessType(Integer wId) {

		StringBuffer sb1 = new StringBuffer();
		/*StringBuffer sb2 = new StringBuffer();
		BusinessTypeExample typeExample = new BusinessTypeExample();
		BusinessTypeExample.Criteria typeCriteria = typeExample.createCriteria();
		typeCriteria.andPidEqualTo(0);
		List<BusinessType> businessTypes = businessTypeMapper.selectByExample(typeExample);*/

		BusinessWorkerExample workerExample = new BusinessWorkerExample();
		BusinessWorkerExample.Criteria workCriteria = workerExample.createCriteria();
		workCriteria.andWIdEqualTo(wId);
		List<BusinessWorker> businessWorkers = businessWorkerMapper.selectByExample(workerExample);
		//List<Integer> bIds = new ArrayList<>();
		if (businessWorkers != null && businessWorkers.size() > 0) {
			for (BusinessWorker bw : businessWorkers) {
				//bIds.add(bw.getbId());
				BusinessType bt = businessTypeMapper.selectByPrimaryKey(bw.getbId());
				if (bt != null) {
					sb1.append(bt.getbName()).append("、");
				}
			}
		}
		if (sb1.length() > 0) {
			return sb1.toString().substring(0, sb1.toString().lastIndexOf("、"));
		}
		return sb1.toString();
	}

	/**
	 * 获取师傅星级，师傅星级为最近评价的十单订单的评分平均值
	 * @return
	 */
	private String getStars(Integer wId) {
		CustomerScoreExample example = new CustomerScoreExample();
		CustomerScoreExample.Criteria criteria = example.createCriteria();
		criteria.andWIdEqualTo(wId);
		example.setLimitStart(0);
		example.setPageSize(10);
		example.setOrderByClause("ASSESS_TIME desc");

		List<CustomerScore> scores = customerScoreMapper.selectByExample(example);
		if (scores != null && scores.size() > 0) {
			int score = 0;
			for (CustomerScore cs : scores) {
				score += cs.getStars();
			}
			double avgScore = score/scores.size();
			return format.format(avgScore);
		} else {
			return "5.0";
		}
	}

	@Override
	public Map<String, Object> queryWorkerInfo(Integer workerId) {

		Map<String, Object> result = new HashMap<>();
		Worker worker = workerMapper.selectByPrimaryKey(workerId);
		if (worker != null) {
			result.put("worker", worker);
			if ("man".equals(worker.getSex())) {
				result.put("sex", "男");
			} else {
				result.put("sex", "女");
			}
			String serviceAddr = getServiceAddress(worker.getProvinceId(), worker.getCityId(), worker.getId());
			result.put("addr", serviceAddr);
			String serviceType = getBusinessType(worker.getId());
			result.put("serviceType", serviceType);
			getOrderInfo(worker.getId(), result);
		}

		return result;
	}

	private void getOrderInfo(Integer wId, Map<String, Object> map) {
		List<Integer> states = new ArrayList<>();
		states.add(OrderStateEnum2.ALREADY_ORDER.getValue());
		states.add(OrderStateEnum2.FINISHED.getValue());
		states.add(OrderStateEnum2.CLOSE.getValue());
		states.add(OrderStateEnum2.IN_SERVICE.getValue());
		states.add(OrderStateEnum2.WAIT_CONFIRM.getValue());
		CustomerOrderinfoExample orderinfoExample = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria orderCriteria = orderinfoExample.createCriteria();
		orderCriteria.andStateIn(states).andWUidEqualTo(wId);
		List<CustomerOrderinfo> orderinfos = customerOrderinfoMapper.selectByExample(orderinfoExample);
		if (orderinfos != null && orderinfos.size() > 0) {
			int totalOrders = orderinfos.size();
			int settledOrders = 0;
			int peddingSettleOrders = 0;
			double totalIncome = 0.0;
			double settledMoney = 0.0;
			double peddingSettleModney = 0.0;
			for (CustomerOrderinfo order : orderinfos) {
				if (OrderStateEnum2.FINISHED.getValue().equals(order.getState()) || OrderStateEnum2.CLOSE.getValue().equals(order.getState())) {
					totalIncome += order.getMoney().doubleValue();
				}
				if (OrderStateEnum2.CLOSE.getValue().equals(order.getState())) {
					settledOrders++;
					settledMoney += order.getMoney().doubleValue();
				} else if (OrderStateEnum2.FINISHED.getValue().equals(order.getState())) {
					peddingSettleOrders++;
					peddingSettleModney += order.getMoney().doubleValue();
				}
			}
			map.put("totalOrders", totalOrders);
			map.put("totalIncome", format2.format(totalIncome));
			map.put("settledOrders", settledOrders);
			map.put("settleMoney", format2.format(settledMoney));
			map.put("peddingOrders", peddingSettleOrders);
			map.put("peddingMoney", format2.format(peddingSettleModney));
		} else {
			map.put("totalOrders", 0);
			map.put("totalIncome", format2.format(0.00));
			map.put("settledOrders", 0);
			map.put("settleMoney", format2.format(0.00));
			map.put("peddingOrders", 0);
			map.put("peddingMoney", format2.format(0.00));
		}
	}

	/**
	 * 删除工人信息
	 * @param workerId
	 * @return
	 */
	@Override
	public int delWorker(Integer workerId) {
		List<Integer> states = new ArrayList<>();
		states.add(OrderStateEnum2.ALREADY_ORDER.getValue());
		states.add(OrderStateEnum2.IN_SERVICE.getValue());
		states.add(OrderStateEnum2.WAIT_CONFIRM.getValue());
		states.add(OrderStateEnum2.FINISHED.getValue());
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andWUidEqualTo(workerId).andStateIn(states)
				.andIsdeleteEqualTo(false);
		List<CustomerOrderinfo> orderinfos = customerOrderinfoMapper.selectByExample(example);
		if (orderinfos != null && orderinfos.size() > 0) {
			return 2;
		}
		Worker worker = workerMapper.selectByPrimaryKey(workerId);
		if (worker != null) {
			worker.setDelFlag(true);
			worker.setUpdateTime(new Date());
			return workerMapper.updateByPrimaryKeySelective(worker);
		}
		return 0;
	}

	/**
	 * 查询工人的订单评价信息
	 * @param workerId
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageBean queryWorkerAssess(Integer workerId, int page, int pageSize) {
		List<Map<String, Object>> result = new ArrayList<>();
		CustomerScoreExample scoreExample = new CustomerScoreExample();
		CustomerScoreExample.Criteria scoreCriteria = scoreExample.createCriteria();
		scoreCriteria.andWIdEqualTo(workerId);
		scoreExample.setOrderByClause("ASSESS_TIME desc");
		scoreExample.setLimitStart((page-1)*pageSize);
		scoreExample.setPageSize(pageSize);

		List<CustomerScore> scores = customerScoreMapper.selectByExample(scoreExample);

		int count = customerScoreMapper.countByExample(scoreExample);
		if (scores != null && scores.size() > 0) {
			for (CustomerScore cs : scores) {
				Map<String, Object> map = new HashMap<>();
				map.put("assessTime", TimeFormatUtil.dateToStrFull(cs.getAssessTime()));
				map.put("stars", cs.getStars());
				map.put("message", cs.getMessage());
				getOrderType(cs.getOrderNo(), map);
				String lableIds = cs.getLableIds();
				if (StringUtils.isNotBlank(lableIds)) {
					String[] ids = lableIds.split(",");
					//List<Integer> lIds = new ArrayList<>();
					StringBuffer sb = new StringBuffer();
					for (String id : ids) {
						//lIds.add(Integer.parseInt(id));
						AssessLable al = assessLableMapper.selectByPrimaryKey(Integer.parseInt(id));
						sb.append(al.getName()).append("、");
					}
					String lables = sb.toString().substring(0, sb.toString().lastIndexOf("、"));
					map.put("lable", lables);
				}
				result.add(map);
			}
		}
		PageBean<List<Map<String, Object>>> pageBean = new PageBean<>(page, pageSize, count, result);
		return pageBean;
	}

	private void getOrderType(String orderNo, Map<String, Object> map) {
		CustomerOrderinfoExample example = new CustomerOrderinfoExample();
		CustomerOrderinfoExample.Criteria criteria = example.createCriteria();
		criteria.andOrderNoEqualTo(orderNo);
		List<CustomerOrderinfo> orderinfos = customerOrderinfoMapper.selectByExample(example);
		if (orderinfos != null && orderinfos.size() > 0) {
			StringBuffer sb = new StringBuffer();
			map.put("serviceTime", TimeFormatUtil.dateToStrFull(orderinfos.get(0).getServiceTime()));
			String bid = orderinfos.get(0).getBids();
			Business business = businessMapper.selectByPrimaryKey(Integer.parseInt(bid));
			if (business != null) {
				BusinessType btb = businessTypeMapper.selectByPrimaryKey(business.getPid());
				if (btb != null) {
					BusinessType bta = businessTypeMapper.selectByPrimaryKey(btb.getPid());
					if (bta != null) {
						 sb.append(bta.getbName()).append("-");
					}
					sb.append(btb.getbName()).append("-");
				}
				sb.append(business.getbName());
				map.put("bType", sb.toString());
			}
		}
	}

	@Override
	public Map<String, Object> editWorker(Integer workerId) {

		Map<String, Object> result = new HashMap<>();
		Worker worker = workerMapper.selectByPrimaryKey(workerId);
		if (worker != null) {
			result.put("worker", worker);
			BusinessWorkerExample businessWorkerExample = new BusinessWorkerExample();
			BusinessWorkerExample.Criteria busCriteria = businessWorkerExample.createCriteria();
			busCriteria.andWIdEqualTo(workerId);
			List<BusinessWorker> businessWorkers = businessWorkerMapper.selectByExample(businessWorkerExample);
			result.put("busType", businessWorkers);
			if (businessWorkers != null && businessWorkers.size() > 0) {
				StringBuffer sb = new StringBuffer();
				for(BusinessWorker bw : businessWorkers) {
					sb.append(bw.getbId()).append(",");
				}
				result.put("busIds", sb.toString());
			}

			WorkerAreaExample areaExample = new WorkerAreaExample();
			WorkerAreaExample.Criteria areaCriteria = areaExample.createCriteria();
			areaCriteria.andWIdEqualTo(workerId);
			List<WorkerArea> workerAreas = workerAreaMapper.selectByExample(areaExample);
			if (workerAreas != null && workerAreas.size() > 0) {
				//List<String> areaIds = new ArrayList<>();
				StringBuffer sb = new StringBuffer();
				for (WorkerArea area : workerAreas) {
					sb.append(area.getAreaId()).append(",");
				}
				result.put("areaIds", sb.toString());
			}
			result.put("areas", workerAreas);
		}
		return result;
	}
}
